﻿
using NewLand;
using System;
using System.Drawing;
using System.IO;
using System.IO.Ports;
using System.Windows.Forms;

namespace ConfExpertEn
{
    public partial class frmMain : Form
    {
        public frmMain()
        {
            InitializeComponent();
        }


        NewLandBarcode newLand = null;

        string Argox = string.Empty;
        string Leica = string.Empty;
        string InputA = String.Empty;
        static string InputB = string.Empty;
        //SerialPort portA;
        SerialPort portL;
        byte[] ack = new byte[] { 0x63, 0x66, 0x6d, 0x0d, 0x0a };   //client'ın göndermesi gereken confirmasyon
        int shelfId = 0;
        decimal en = 0.0m;
        delegate void SetTextCallback(string text);

        void Init()
        {
            FileInfo fi = new FileInfo("c:\\ce\\ceEn.dat");
            string[] lines = File.ReadAllLines(fi.FullName);

            foreach (string line in lines)
            {
                if (line.Contains("Argox"))
                    Argox = line.Substring(line.IndexOf("COM"));
                else if (line.Contains("Leica") || line.Contains("Disto"))
                    Leica = line.Substring(line.IndexOf("COM"));
                if (line.Contains("DatabaseNamePostFix"))
                    DataAccess.DatabaseNamePostFix = line.Replace("DatabaseNamePostFix", "").Replace("\t", "").Trim();
                else if (line.Contains("Gate"))
                    DataAccess.Gate = line.Replace("Gate", "").Replace("\t", "").Trim();
            }

            DataAccess.Init();
        }

        void frmMain_Load(object sender, EventArgs e)
        {
            try
            {

                Init();

                this.FormClosing += new FormClosingEventHandler(frmMain_FormClosing);

                newLand = new NewLandBarcode(this);
                newLand.CihazEkle(1, Argox.Replace("COM", "").ToInt());

                //portA = new System.IO.Ports.SerialPort(Argox);
                //portA.BaudRate = 38400;
                //portA.DataBits = 8;
                //portA.Parity = Parity.None;
                //portA.StopBits = StopBits.One;
                //portA.Handshake = Handshake.RequestToSend;
                //portA.DtrEnable = true;
                //if (!portA.IsOpen)
                //    portA.Open();

                newLand.BarcodeRead += cihaz_BarcodeRead;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                // MessageBox.Show("Serial port " + portA.PortName + " ile bağlantı kurulamadı!");
            }

            try
            {
                portL = new System.IO.Ports.SerialPort(Leica);
                portL.BaudRate = 9600;
                portL.DataBits = 8;
                portL.Parity = Parity.None;
                portL.StopBits = StopBits.One;
                portL.Handshake = Handshake.None;
                portL.DtrEnable = true;
                if (!portL.IsOpen)
                    portL.Open();
            }
            catch
            {
                MessageBox.Show("Serial port " + portL.PortName + " ile bağlantı kurulamadı!");
            }

            //portA.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(portA_DataReceived);
            portL.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(portL_DataReceived);
        }

        private void cihaz_BarcodeRead(int Barcode, DateTime Tarih, int CihazNo)
        {
            this.BeginInvoke(new SetTextCallback(SetText), new object[] { Barcode.ToString() });
        }




        void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {

            //portA.Close();
            portL.Close();
        }

        //void portA_DataReceived(object sender, SerialDataReceivedEventArgs e)
        //{
        //    InputA += portA.ReadExisting();

        //    string s2 = InputA; // val.Replace("\r\n", "");



        //    string s3 = s2.TrimStart(new char[] { '0' });
        //    string s4 = s3.Substring(0, s3.Length - 1);

        //    string[] vals = s4.Split(",".ToCharArray());
        //    string[] dates = vals[0].Split("/".ToCharArray());
        //    string[] times = vals[1].Split(":".ToCharArray());
        //    DateTime date = new DateTime(
        //                                      int.Parse(dates[0].ToString())
        //                                    , int.Parse(dates[1].ToString())
        //                                    , int.Parse(dates[2].ToString())
        //                                    , int.Parse(times[0].ToString())
        //                                    , int.Parse(times[1].ToString())
        //                                    , int.Parse(times[2].ToString())

        //                                    );


        //    if (vals[2].Contains("\r") && vals[2].Length == 13)
        //    {
        //        this.BeginInvoke(new SetTextCallback(SetText), new object[] { vals[2] });
        //        InputA = string.Empty;
        //    }
        //}

        void portL_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int DataLength = portL.BytesToRead;
            byte[] input = new byte[DataLength]; // input buffer
            portL.Read(input, 0, DataLength);
            System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
            InputB += encoding.GetString(input);

            if (InputB.Contains(" " + Environment.NewLine))
            {
                portL.Write(ack, 0, 5); // send acknowledge byte
                this.Invoke(new MethodInvoker(() => txtEn.Text = InputB.Substring(InputB.IndexOf(" " + Environment.NewLine) - 5, 5)));
                InputB = string.Empty;
            }
        }

        void SetText(string text)
        {
            // MessageBox.Show("*" + text + "*");
            // text = text.Substring(0, text.Length - 2);  //sondaki parity bitini ve carriage return ü at!

            int okunan = 0;
            int.TryParse(text, out okunan);
            if (okunan > 1e9)
            {
                shelfId = okunan - 1000000000;
                txtRaf.Text = shelfId.ToString();
                txtRaf.Text = DataAccess.GetShelfName(shelfId);
            }
            else if (okunan > 0)
            {
                if (txtRaf.Text.Trim() == string.Empty || txtEn.Text.Trim() == string.Empty)
                {
                    string path = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + "\\Notify.wav";
                    if (!File.Exists(path))
                        File.WriteAllBytes(path, Properties.Resources.Notify);

                    Wav.Play(path);
                }

                else
                {

                    en = int.Parse(txtEn.Text) / 10.0m;

                    lblTop.Text = okunan.ToString();
                    lblTop.BackColor = SystemColors.ControlDarkDark;

                    try
                    {

                        DataAccess.UpdateEn(okunan, shelfId, en);
                    }
                    catch (ApplicationException ex)
                    {
                        MessageBox.Show(ex.ToString());
                    }
                    finally
                    {
                        lblTop.BackColor = SystemColors.ControlDark;
                        txtEn.Text = string.Empty;
                    }
                }
            }
        }
    }
}